//
//  NetWorkingTools.swift
//  LVWeibo
//
//  Created by lv on 15/6/26.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit
import AFNetworking

/// 获取当前登录用户及其所关注用户的最新微博
private let WB_Home_Timeline_URL = "2/statuses/home_timeline.json"

class NetWorkTools: AFHTTPSessionManager {

    private static let instance: NetWorkTools = {
        // baseURL 字符串 以 / 结尾
        let urlString = "https://api.weibo.com/"
        let baseURL = NSURL(string: urlString)!
        let tools = NetWorkTools(baseURL: baseURL)
        
        // 设置默认反序列化格式
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        return tools
    }()
    
    // 全局访问
    class var sharedNetWorkTools:NetWorkTools {
        return instance
    }
    
    //MARK:- 发布微博
    ///  文本微博
    func postStatus(text: String,image: UIImage?,finished:(error: NSError?) -> ()) {
        
        // 判断token是否有值
        assert(sharedUserAccount?.access_token != nil, "必须传入token")
        
        var urlString = "2/statuses/"
        let parameters = ["access_token": sharedUserAccount!.access_token,"status": text]
        // 文本微博
        if image == nil {
            
            urlString += "update.json"
            // 发送请求
            POST(urlString, parameters: parameters, success: { (_, JSON) -> Void in
                finished(error: nil)
                
                }) { (_, error) -> Void in
                    
                    print(error)
                    finished(error: error)
            }
        }else {
            // 图片微博
            urlString += "upload.json"
            POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                let data = UIImagePNGRepresentation(image!)
                
                formData.appendPartWithFileData(data, name: "pic", fileName: "helloworld", mimeType: "application/octect-stream")
                
                }, success: { (_, _) -> Void in
                    
                    finished(error: nil)
                }, failure: { (_, error) -> Void in
                    
                    finished(error: error)
            })
        }
    }
    
    // MARK:- 加载微博数据
    // 正在加载数据标记
    private var isLoadData = false
    func loadStatuses(since_id: Int,max_id: Int,finished:(array: [[String:AnyObject]]?,error: NSError?) -> ()) {
        
        if isLoadData {
            print("正在加载数据")
            return
        }
        // 定义请求参数(字典)
        var parameters = access_token()
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            parameters["since_id"] = "0"
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        // 异步请求网络数据
        GET(WB_Home_Timeline_URL, parameters: parameters, success: { (_, JSON) -> Void in
            
            self.isLoadData = false
            
            // 获取微博数据转模型并回调
            if let array = JSON["statuses"] as? [[String:AnyObject]] {
                
                // 直接将回调数组
                finished(array: array, error: nil)
                return
            }
            // 空数据
            finished(array: nil, error: nil)
            
            }) { (_, error) -> Void in
                self.isLoadData = false
                print(error)
                finished(array: nil, error: error)
        }
    }
    
    //MARK:- 私有辅助函数 - 生成access_token
    private func access_token() -> [String: String] {
        // 断言
        assert(sharedUserAccount != nil, "用户没有登录")
        return ["access_token":sharedUserAccount!.access_token]
    }

}
